#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename:git_bran_helper.py
# function:分支助手，检测不同分支的信息

##########

import sys
import os
import subprocess

sys.path.append('.')
# 自定义公共函数
# from public import *
from base.public import *

#####定义结束标志，标志未修改时为正常退出，默认为异常值，正常值为0
quitflag = 1


def setquitflag(flag):
    global quitflag
    quitflag = flag


def over():
    global add
    printlntips("quitflag", quitflag, False)
    if 0 != quitflag:
        print('异常退出，！！！！！！！！')
    else:
        print('正常结束，★★★★★★★★★★★★★★★★')


atexit.register(over)


########main proc


def git_diff(branch1, branch2):
    try:
        # 获取两个分支的差异
        diff_output = subprocess.check_output(['git', 'diff', branch1, branch2], timeout=30)
        return diff_output.decode('utf-8')
    except subprocess.CalledProcessError as e:
        print("Exception on process, rc=", e.returncode, "output=", e.output)
        return ''



def search_content(branch, content):
    try:
        # 查看分支是否包含指定内容
        grep_output = subprocess.check_output(['git', 'grep', content, branch], timeout=30)
        # print('grep_output:%s\n' % grep_output)
        return True, grep_output.decode('utf-8')
    except Exception as e:
        # print('Error:%s\n' % e)
        return False, ''


#查找一个分支的内容
#返回值分别为:
#1.整体函数的返回值：True(成功)/False(失败)
#2.查找内容的结果：True:有数据，False:无数据
#3.查找结果内容
def search_content_branch(branch, content):
    branch1 = branch
    search_text = content
    try:
        # diff_result = git_diff(branch1, branch2)
        # print(f"分支{branch1}和分支{branch2}的差异为：\n{diff_result}")
        # diff_result = f"分支{branch1}和分支{branch2}的差异为：\n{diff_result}"

        return_result, search_result = search_content(branch1, search_text)
        if True == return_result:
            # print(f"分支{branch1}中包含内容'{search_text}':\n{search_result}")
            search_result = f"分支{branch1}中包含内容'{search_text}':\n{search_result}"
        else:
            # print(f"分支{branch1}中不包含内容'{search_text}'")
            search_result = f"分支{branch1}中不包含内容'{search_text}'"
        return True, return_result, search_result
    except Exception as e:
        print('\n\t:(,  Error:%s\n' % e)
        return False, "错误" + e


def gitbranchescheck(gotopath,branches, search_text, isshowdiff):

    if(0 == len(gotopath)):
        return False, "请输入路径","",False,"",False,""


    brancheslist = branches.split(';')
    if len(brancheslist) != 2:
        return False,"分支数量要求为两个","",False,"",False,""

    branch1 = brancheslist[0]
    branch2 = brancheslist[1]

    try:
        if os.path.exists(gotopath):
            os.chdir(gotopath)
        else:
            print("gotopath no exist:%s" % gotopath)
            return False,"检查的git路径不存在，请检查","","","","",""
    except Exception as e:
        print('\n\t:(, change path Error:%s\n' % e)
        return False, "切换路径失败" + e,"",False,"",False,""

    try:
        diff_result = ""
        if(len(isshowdiff)):
            diff_result = git_diff(branch1, branch2)
            print(f"分支{branch1}和分支{branch2}的差异为：\n{diff_result}")
            diff_result =  f"分支{branch1}和分支{branch2}的差异为：\n{diff_result}"

        #第1个分支包含的内容
        whole_result1, return_result1, search_result1 = search_content_branch(branch1, search_text)
        whole_result2, return_result2, search_result2 = search_content_branch(branch2, search_text)


        # resultlist = [diff_result, return_result1, search_result1, return_result2, whole_result2]
        return True, "查找成功", diff_result, return_result1, search_result1, return_result2, search_result2

    except Exception as e:
        print('\n\t:(,  Error:%s\n' % e)
        return False, "其它错误" + e,"",False,"",False,""



if __name__ == '__main__':
    print("===========main proc===========\n" * 3)
    if len(sys.argv) < 5:
        print("usage: ./eg.sh execpath branch1 branch2 checkcontent\n")
        exit(0)

    print("argv:%s" % sys.argv)
    gotopath = ""
    branch1 = ""
    branch2 = ""
    search_text = ""
    args = sys.argv
    try:
        gotopath = args[1]
        branch1 = args[2]
        branch2 = args[3]
        search_text = args[4]
        print('==>check path:%s' % (gotopath))
        print('   compare branchs: %s %s' % (branch1, branch2))
        print('   search:%s' % (search_text))
    except Exception as e:
        print('\n\t:(, input param Error:%s\n' % e)
        exit(1)

    try:
        if os.path.exists(gotopath):
            os.chdir(gotopath)
        else:
            print("gotopath no exist:%s" % gotopath)
            exit(1)
    except Exception as e:
        print('\n\t:(, change path Error:%s\n' % e)
        exit(1)

    try:
        diff_result = git_diff(branch1, branch2)
        print(f"分支{branch1}和分支{branch2}的差异为：\n{diff_result}")

        return_result, search_result = search_content(branch1, search_text)
        if True == return_result:
            print(f"分支{branch1}中包含内容'{search_text}':\n{search_result}")
        else:
            print(f"分支{branch1}中不包含内容'{search_text}'")

    except Exception as e:
        print('\n\t:(,  Error:%s\n' % e)
        exit(1)

    # 设置成功标志
    setquitflag(0)
